<template>
  <div class="experiences-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>体验项目列表</span>
          <el-button-group>
            <el-button type="primary" @click="handleAdd">添加项目</el-button>
            <el-button type="success" @click="exportData">导出数据</el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="项目名称">
          <el-input v-model="searchForm.keyword" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="体验分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类">
            <el-option 
              v-for="item in categories" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格区间">
          <el-input-number
            v-model="searchForm.minPrice"
            :min="0"
            placeholder="最低价"
            style="width: 130px"
          />
          <span class="mx-2">-</span>
          <el-input-number
            v-model="searchForm.maxPrice"
            :min="0"
            placeholder="最高价"
            style="width: 130px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="sortedTableData"
        v-loading="loading"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无体验项目数据" 
              :image-size="200"
            >
              <div class="empty-text">还没有添加任何体验项目</div>
              <div class="empty-subtext">添加体验项目让游客获得更丰富的旅游体验</div>
              <el-button type="primary" @click="handleAdd" class="mt-4">添加第一个体验项目</el-button>
            </el-empty>
          </div>
        </template>
        <el-table-column label="体验项目" min-width="300">
          <template #default="{ row }">
            <div class="experience-info">
              <el-image
                :src="row.cover"
                :preview-src-list="[row.cover]"
                class="experience-image"
                fit="cover"
              />
              <div class="experience-detail">
                <h3 class="experience-title">{{ row.title }}</h3>
                <p class="experience-desc">{{ row.description }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            <el-tag>{{ getCategoryLabel(row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="price"
          label="价格"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>¥{{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="预约情况"
          width="150"
          align="center"
          sortable="custom"
          prop="bookings"
        >
          <template #default="{ row }">
            <div>{{ row.bookings }} / {{ row.capacity }}</div>
            <div class="text-secondary">已预约/容量</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === "active" ? "上架" : "下架" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" size="small" @click="handleEdit(row)"
                >编辑</el-button
              >
              <el-button type="danger" size="small" @click="handleDelete(row)"
                >删除</el-button
              >
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import service from "@/api/axios";
import * as XLSX from 'xlsx';

const router = useRouter();

// 搜索表单
const searchForm = reactive({
  keyword: "",
  category: "",
  minPrice: null,
  maxPrice: null,
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const categories = ref([]);

// 排序相关
const sortConfig = reactive({
  prop: "",
  order: "",
});

// 获取排序后的表格数据
const sortedTableData = computed(() => {
  const list = [...tableData.value];
  if (!sortConfig.prop) return list;

  return list.sort((a, b) => {
    let aValue = a[sortConfig.prop];
    let bValue = b[sortConfig.prop];

    // 处理数字类型
    if (["price", "bookings"].includes(sortConfig.prop)) {
      aValue = Number(aValue);
      bValue = Number(bValue);
    }

    if (sortConfig.order === "ascending") {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });
});

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  sortConfig.prop = prop;
  sortConfig.order = order;
};

// 获取分类标签
const getCategoryLabel = (categoryId) => {
  const category = categories.value.find(item => item.id === categoryId);
  return category ? category.name : categoryId;
};

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await service.get('/admin/experiences/categories', {
      params: { pageSize: 100 }
    });
    if (res.code === 200 && res.data) {
      categories.value = res.data.list || [];
    } else {
      // 使用测试数据
      categories.value = [
        { id: 1, name: "文化体验" },
        { id: 2, name: "手工艺" },
        { id: 3, name: "农事体验" },
        { id: 4, name: "美食制作" },
      ];
    }
  } catch (error) {
    console.error("获取分类列表失败", error);
    // 使用测试数据
    categories.value = [
      { id: 1, name: "文化体验" },
      { id: 2, name: "手工艺" },
      { id: 3, name: "农事体验" },
      { id: 4, name: "美食制作" },
    ];
  }
};

// 获取数据列表
const fetchData = async () => {
  loading.value = true;
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchForm.keyword,
      categoryId: searchForm.category,
      minPrice: searchForm.minPrice,
      maxPrice: searchForm.maxPrice,
      sort: sortConfig.prop,
      order: sortConfig.order
    };
    
    const res = await service.get('/admin/experiences/list', { params });
    
    if (res.code === 200 && res.data) {
      tableData.value = res.data.list || [];
      total.value = res.data.total || 0;
    } else {
      // 使用测试数据
      tableData.value = [
        {
          id: 1,
          title: "贵港传统手工艺体验",
          description: "体验贵港传统手工艺制作过程",
          cover: "https://example.com/image1.jpg",
          category: 2,
          price: 88,
          bookings: 12,
          capacity: 20,
          status: "active",
        },
        {
          id: 2,
          title: "壮族特色美食制作体验",
          description: "学习制作贵港传统壮族美食",
          cover: "https://example.com/image2.jpg",
          category: 4,
          price: 120,
          bookings: 8,
          capacity: 15,
          status: "active",
        },
        {
          id: 3,
          title: "贵港水乡农事体验",
          description: "体验贵港特色农事活动",
          cover: "https://example.com/image3.jpg",
          category: 3,
          price: 75,
          bookings: 5,
          capacity: 25,
          status: "inactive",
        },
      ];
      total.value = 3;
    }
  } catch (error) {
    console.error("获取数据失败", error);
    // 使用测试数据
    tableData.value = [
      {
        id: 1,
        title: "贵港传统手工艺体验",
        description: "体验贵港传统手工艺制作过程",
        cover: "https://example.com/image1.jpg",
        category: 2,
        price: 88,
        bookings: 12,
        capacity: 20,
        status: "active",
      },
      {
        id: 2,
        title: "壮族特色美食制作体验",
        description: "学习制作贵港传统壮族美食",
        cover: "https://example.com/image2.jpg",
        category: 4,
        price: 120,
        bookings: 8,
        capacity: 15,
        status: "active",
      },
      {
        id: 3,
        title: "贵港水乡农事体验",
        description: "体验贵港特色农事活动",
        cover: "https://example.com/image3.jpg",
        category: 3,
        price: 75,
        bookings: 5,
        capacity: 25,
        status: "inactive",
      },
    ];
    total.value = 3;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = "";
  searchForm.category = "";
  searchForm.minPrice = null;
  searchForm.maxPrice = null;
  handleSearch();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 添加
const handleAdd = () => {
  router.push("/admin/content/experiences/edit");
};

// 编辑
const handleEdit = (row) => {
  router.push(`/admin/content/experiences/edit?id=${row.id}`);
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该体验项目吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const res = await service.delete(`/admin/experiences/${row.id}`);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        fetchData();
      } else {
        ElMessage.error(res.message || "删除失败");
      }
    } catch (error) {
      console.error("删除失败", error);
      ElMessage.error("删除失败");
    }
  });
};

// 导出数据
const exportData = () => {
  // 前端导出Excel
  try {
    // 准备导出数据
    const exportItems = tableData.value.map(item => ({
      '项目名称': item.title,
      '项目分类': getCategoryLabel(item.category),
      '价格': item.price,
      '预约人数': item.bookings,
      '容量': item.capacity,
      '状态': item.status === 'active' ? '上架' : '下架',
      '描述': item.description
    }));
    
    // 创建工作簿和工作表
    const worksheet = XLSX.utils.json_to_sheet(exportItems);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '体验项目列表');
    
    // 设置列宽
    const colWidth = [
      { wch: 30 }, // 项目名称
      { wch: 15 }, // 项目分类
      { wch: 10 }, // 价格
      { wch: 10 }, // 预约人数
      { wch: 10 }, // 容量
      { wch: 10 }, // 状态
      { wch: 50 }  // 描述
    ];
    worksheet['!cols'] = colWidth;
    
    // 导出Excel文件
    XLSX.writeFile(workbook, `体验项目列表_${new Date().toISOString().split('T')[0]}.xlsx`);
    
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败", error);
    ElMessage.error("导出失败");
  }
};

// 初始化
onMounted(() => {
  fetchCategories();
  fetchData();
});
</script>

<style scoped>
.experiences-management {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 40px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.search-form {
  background-color: var(--el-bg-color);
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.experience-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.experience-image {
  width: 140px;
  height: 90px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.experience-image:hover {
  transform: scale(1.02);
}

.experience-detail {
  flex: 1;
  min-width: 0;
}

.experience-title {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.experience-desc {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.5;
}

.text-secondary {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

.pagination-container {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid var(--el-border-color-light);
  display: flex;
  justify-content: flex-end;
}

.mx-2 {
  margin: 0 8px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
  background-color: var(--el-bg-color);
  font-weight: 600;
}

:deep(.el-table__row) {
  transition: background-color 0.3s ease;
}

:deep(.el-table__row:hover) {
  background-color: var(--el-color-primary-light-9) !important;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 12px;
  height: 24px;
  line-height: 24px;
}

:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 13px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-input-number) {
  width: 130px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .experiences-management {
    padding: 12px;
  }

  .search-form {
    padding: 16px;
  }

  .experience-image {
    width: 100px;
    height: 70px;
  }

  .experience-title {
    font-size: 14px;
  }

  .experience-desc {
    font-size: 12px;
    -webkit-line-clamp: 1;
  }
}

/* 优化对话框样式 */
:deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: 90vh;
  max-width: 90vw;
}

:deep(.el-dialog__body) {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

:deep(.el-dialog__header) {
  padding: 20px;
  margin: 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

:deep(.el-dialog__footer) {
  padding: 20px;
  margin: 0;
  border-top: 1px solid var(--el-border-color-lighter);
}

.empty-state {
  padding: 40px 0;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
